package com.sifou.courses.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sifou.courses.dto.SeckillGoodsDto;
import com.sifou.courses.dto.SeckillOrderDto;
import com.sifou.courses.repository.entity.TSeckillOrder;
import com.sifou.courses.repository.mapper.TSeckillOrderMapper;
import com.sifou.courses.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liuzhongxu
 * @date 2020/8/18
 */
@SuppressWarnings("AlibabaRemoveCommentedCode")
@Slf4j
@Service
public class OrderServiceImpl implements IOrderService {

    @Resource
    private TSeckillOrderMapper orderMapper;

    @Override
    public SeckillOrderDto getOrder(Integer orderId) {
        TSeckillOrder orderEntity = orderMapper.selectById(orderId);
        SeckillOrderDto orderDto = new SeckillOrderDto();
        BeanUtils.copyProperties(orderEntity, orderDto);
        return orderDto;
    }

    @Override
    public Integer createOrder(SeckillGoodsDto goodsDto) {
        TSeckillOrder tSeckillOrder = new TSeckillOrder();
        tSeckillOrder.setGoodsId(goodsDto.getId());
        tSeckillOrder.setName(goodsDto.getName());
        tSeckillOrder.setStatus(0);
        orderMapper.insert(tSeckillOrder);
        log.debug("创建订单：" + tSeckillOrder);
        return tSeckillOrder.getId();
    }

    @Override
    public List<SeckillOrderDto> getOrders(int page, int size) {
        IPage<TSeckillOrder> orderPage = new Page<>(page, size);
        orderPage = orderMapper.selectPage(orderPage, Wrappers.<TSeckillOrder>lambdaQuery().orderByDesc(TSeckillOrder::getId));
        List<TSeckillOrder> orderList = orderPage.getRecords();
        List<SeckillOrderDto> orderDtoList = new ArrayList<>();
        orderList.forEach(orderEntity->{
            SeckillOrderDto orderDto = new SeckillOrderDto();
            BeanUtils.copyProperties(orderEntity, orderDto);
            orderDtoList.add(orderDto);
        });
        return orderDtoList;
    }

    @Override
    public Integer updateOrderStatus(int orderId, int status) {
        TSeckillOrder tSeckillOrder = new TSeckillOrder();
        tSeckillOrder.setId(orderId);
        tSeckillOrder.setStatus(status);
        log.debug("更新订单状态：" + tSeckillOrder);
        return orderMapper.updateById(tSeckillOrder);
    }
}
